import { createRouter, createWebHistory } from 'vue-router';
import Forum from '../views/Forum.vue';
import LoginPage from '../views/LoginPage.vue'
import HomePage from '../views/HomePage.vue'
// 导入注册页面组件
import RegisterPage from '../views/RegisterPage.vue'
// 导入个人信息完善页面组件
import ProfileCompletePage from '../views/ProfileCompletePage.vue'
// 导入用户主页组件
import UserProfile from '../views/UserProfile.vue'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'Login', component: LoginPage },
  { path: '/home', name: 'home', component: HomePage, meta: { requiresAuth: true }},
  // 添加注册页面路由
  { path: '/register', name: 'Register', component: RegisterPage },
  // 添加个人信息完善页面路由
  { path: '/profile-complete', name: 'ProfileComplete', component: ProfileCompletePage, meta: { requiresAuth: true }},
  // 添加用户主页路由
  { path: '/user/:userId', name: 'UserProfile', component: UserProfile, meta: { requiresAuth: true }},
  { path: '/forum', name: 'Forum', component: Forum }
]

const router = createRouter({
  history: createWebHistory('/SchoolHelper/'),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  
  // 如果用户已登录但要访问登录页面，重定向到首页
  if (to.path === '/login' && token) {
    next('/home');
    return;
  }
  
  // 如果访问需要认证的页面
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      // 清除可能存在的历史记录，防止用户通过前进按钮回到应用
      if (from.path !== '/login') {
        next({ path: '/login', replace: true });
      } else {
        next('/login');
      }
    } else {
      next();
    }
  } else {
    next();
  }
});

// 添加全局后置守卫，用于处理页面跳转后的逻辑
router.afterEach((to, from) => {
  // 如果从应用页面跳转到登录页面，清除浏览器历史记录
  if (from.matched.some(record => record.meta.requiresAuth) && to.path === '/login') {
    // 使用 replace 方法替换当前历史记录，防止用户通过后退按钮回到应用
    window.history.replaceState(null, '', '/login');
  }
});

export default router